package com.silence.gankio.net

import android.os.NetworkOnMainThreadException
import com.silence.gankio.mvp.control.HttpControl
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException


open abstract class BaseObserver<T>(val mView: HttpControl.IHttpView) : Observer<T> {

    private val RESPONSE_CODE_FAILED = -1  //返回数据失败,严重的错误
    private var errorCode: Int = 0
    private var errorMsg = "未知的错误！"



    override fun onSubscribe(d: Disposable) {
        mView.applyDisposable(d)
    }

    override fun onError(e: Throwable) {
        when (e) {
            is SocketTimeoutException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "服务器响应超时"
            }
            is ConnectException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "网络连接异常，请检查网络"
            }
            is UnknownHostException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "无法解析主机，请检查网络连接"
            }
            is UnknownServiceException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "未知的服务器错误"
                //飞行模式等
            }
            is IOException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "没有网络，请检查网络连接"
                //主线程不能网络请求，这个很容易发现
            }
            is NetworkOnMainThreadException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "主线程不能网络请求"
                //很多的错误都是extends RuntimeException
            }
            is HttpException -> {
                val httpException = e
                errorCode = httpException.code()
                errorMsg = httpException.message()
            }
            is RuntimeException -> {
                errorCode = RESPONSE_CODE_FAILED
                errorMsg = "运行错误"
            }
        }
        e.printStackTrace()
        onError(errorMsg, errorCode)
    }
    override fun onComplete() {
        mView.onNetFinish()
    }

    fun onError(msg: String, code: Int) {
        mView.onNetError(code, msg)
    }

}